import axios from 'axios'
import router from '@/router/index'
import {ElMessage,ElNotification} from 'element-plus'

export  let baseImgUrl = import.meta.env.VITE_BASE_IMG_URL

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API // api 的 base_url
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json'
    if(config.url.indexOf('/wineApply/downWineTemplate') != -1) {
      config.responseType ='blob'
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 兼容blob下载出错json提示
    if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function(e) {
        const errorMsg = JSON.parse(reader.result).message
        Notification.error({
          title: errorMsg,
          duration: 5000
        })
      }
    } else {
      let code = 0
      try {
        code = error.response.status
      } catch (e) {
        if (error.toString().indexOf('Error: timeout') !== -1) {
          Notification.error({
            title: '网络请求超时',
            duration: 5000
          })
          return Promise.reject(error)
        }
      }
      if (code) {
        if(code===511){
          router.push({ path: '/bind' })
        }else if (code === 401) {
          // store.dispatch('LogOut').then(() => {
          //   // 用户登录界面提示
          //   Cookies.set('point', 401)
          //   location.reload()
          // })
          router.push({ path: '/login' })
        } else if (code === 403) {
          router.push({ path: '/401' })
        } else {
          const errorMsg = error.response.data.body?error.response.data.body:error.response.data.message
          if (errorMsg) {
            ElMessage({ message: errorMsg, type: 'error' })
          }
        }
      } else {
        ElNotification.error({
          title: error.response.data.body,
          duration: 5000
        })
      }
    }
    return Promise.reject(error)
  }
)

export function get(url, data) {
  let params = ''
  for (const key in data) {
    if(key&&data[key]){
      params += key + '=' + data[key] + '&'
    }
  }
  params = params.substr(0, params.length - 1)
  if (data) {
    return service({
      url: url + '?' + params,
      method: 'get'
    })
  } else {
    return service({
      url: url,
      method: 'get'
    })
  }
}

export function post(url, data) {
  return service({
    url: url,
    method: 'post',
    data
  })
}

export function put(url, data) {
  return service({
    url: url,
    method: 'put',
    data
  })
}

export function deleteMethod(url, data) {
  return service({
    url: url,
    method: 'delete',
    data
  })
}

export default service
